//https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
package codeRandomThoughts.剑指Offer58II左旋转字符串;

import java.util.Arrays;

public class Solution {
    public String reverseLeftWords(String s, int n) {
        char[] chars = s.toCharArray();
        String s1 = new String(Arrays.copyOfRange(chars, n, chars.length));
        StringBuffer stringBuffer = new StringBuffer(s1);
        for (int i = 0; i < n; i++) {
            stringBuffer.append(chars[i]);
        }
        return stringBuffer.toString();
    }

    /**
     * 这个方法一般人绝对想不出来
     * 整体反转加局部反转的思想
     * 用StringBuilder效率更高
     * @param s
     * @param n
     * @return
     */
    public String reverseLeftWords2(String s, int n) {
        //反转区间为前n的子串
        int len=s.length();
        StringBuilder sb=new StringBuilder(s);
        reverseString(sb,0,n-1);

        //反转区间为n到末尾的子串
        reverseString(sb,n,len-1);

        //反转整个字符串
        return sb.reverse().toString();
    }
    public void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }
}
